package common

import (
	"github.com/go-redis/redis"
	"go-scripts/config"
	"strconv"
	"fmt"
)

var redisCli *Redis = nil

func (r *Redis) GetRedisClient(db string) (*redis.Client,error) {
	redisConfig := r.conf
	if db == "" {
		error := NewError("库名不能为空", RedisError)
		return nil,error
	}
	dataConfig := redisConfig[db]
	if dataConfig == nil {
		return nil,NewError("库名不存在", RedisError)
	}
	num,err := strconv.Atoi(dataConfig.(map[string]interface{})["DB"].(string))
	if err != nil {
		return nil,err
	}
	dataOption := &redis.Options{
		Addr: dataConfig.(map[string]interface{})["Addr"].(string),
		DB:   num,
		Password: dataConfig.(map[string]interface{})["Password"].(string),
	}
	return redis.NewClient(dataOption),nil
}

type Redis struct {
	conf map[string]interface{}
}

func GetRedis() *Redis {
	if redisCli != nil {
		return redisCli
	}
	fmt.Println("初始化redisCli")
	//初始化redis连接配置
	redisCli = new(Redis)
	conf := config.GetConfig()
	redisCli.conf = conf.GetRedisConfig()
	return redisCli
}
